package com.chinawayltd.ews.sample.web.basicInfo;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
import com.chinawayltd.ews.sample.core.exception.BusinessException;
import com.chinawayltd.ews.sample.model.TBranch;
import com.chinawayltd.ews.sample.model.TLog;
import com.chinawayltd.ews.sample.model.basicInfo.BranchVO;
import com.chinawayltd.ews.sample.service.basicInfo.BranchService;
import com.chinawayltd.ews.sample.service.common.CommonService;
import com.chinawayltd.ews.sample.util.BaseController;
import com.chinawayltd.ews.sample.util.PageData;
import com.chinawayltd.ews.sample.util.ResultModel;
import com.chinawayltd.ews.sample.util.StringUtils;
import com.chinawayltd.ews.sample.util.excel.ExcelGenerateModel;
import com.chinawayltd.ews.sample.util.excel.ExcelObjModel;
import com.chinawayltd.ews.sample.util.excel.ExcelUtils;
import com.chinawayltd.ews.sample.web.query.BranchGirdQuery;
import com.chinawayltd.ews.sample.web.query.LogGirdQuery;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

/**
 * @program: greeProject
 * @description 站点信息Controller
 * @author: xiazj
 * @create: 2018年4月11日 上午11:12:23
 */
@Api(tags = { "站点信息管理API" })
@RestController
@RequestMapping(value = "/web/branch/info")
public class BranchController extends BaseController{

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private BranchService branchService;
    @Autowired
    private CommonService commonService;
    
    @ApiOperation(value = "站点信息列表查询接口")
    @RequestMapping(value = "/loadGirdData", method = { RequestMethod.POST })
    public ResultModel loadGirdData(BranchGirdQuery queryParam) {
        ResultModel model = new ResultModel();
        try {
            List<BranchVO> branchList = branchService.listBranchByPage(queryParam);
            model.setData(new JSONObject().fluentPut("result", branchList));
            model.setPage(queryParam);
        }catch (Exception e){
        	model.setSub_code(1);
			model.setData(new JSONObject().fluentPut("sub_msg", null));
            logger.error("站点列表查询出错！", e);
        }
        return model;
    }
    
    @ApiOperation(value = "站点信息列表导出接口")
    @RequestMapping(value = "/exportGirdData", method = { RequestMethod.POST })
    public void exportGirdData(@RequestBody BranchGirdQuery queryParam, HttpServletRequest request, HttpServletResponse response) {
        try {
        	String sortStr = queryParam.getSortStr();
        	logger.info("站点信息列表导出出错！"+sortStr);
            List<BranchVO> branchList = branchService.listBranchByPage(queryParam);
            ExcelGenerateModel excelModel = new ExcelGenerateModel.Builder(branchList)
                    .cloumnList(queryParam.getCloums()).build();
            Workbook workbook = ExcelUtils.generateExcel(excelModel);
            this.sendWorkbook(workbook, "站点信息列表" , request, response);
        }catch (Exception e){
            logger.error("站点信息列表导出出错！", e);
        }
    }
    
    /**
     * 解析excel2003和2007的数据，并导入到数据库，错误数据导出到前台
     * @author: chenxin
     * @date: 2018年4月25日
     * @param file
     */
    @SuppressWarnings("rawtypes")
    @ApiOperation(value = "站点信息批量导入接口")
	@RequestMapping(value="/readExcel", method = { RequestMethod.POST })
    public Object readExcel(@RequestParam("file")MultipartFile file, HttpServletRequest request, HttpServletResponse response) {
    	JSONObject object = new JSONObject();
    	try {
	    	ExcelObjModel model = ExcelUtils.readExcel(file);
	    	if(model.getCode() !=0){
	    		object.put("state", 400);
		    	object.put("msg", model.getMsg());
				return object.toString();
			}
			// 2、导入数据到数据库
			List<PageData> list = (List)model.getList();
			if(list ==null || list.isEmpty()){
				object.put("state", 400);
		    	object.put("msg", "导入的表不是有效的文件或数据为空");
		    	return object.toString();
			}
			ExcelObjModel result = branchService.insertList(list);
			// 3、导出错误数据
			if(result.getList().size() >0){
		        ExcelGenerateModel excelModel = new ExcelGenerateModel.Builder(result.getList()).cloumnList(result.getCloums()).build();
		        Workbook workbook = ExcelUtils.generateExcel(excelModel);
				this.sendWorkbook(workbook, "站点导入信息" , request, response);
			}
		} catch (BusinessException e) {
		 	object.put("state", 400);
	    	object.put("msg", e.getMessage());
	    	return object.toString();
		} catch (IOException e) {
			object.put("state", 400);
	    	object.put("msg", "导入数据接口出错");
	    	return object.toString();
		} catch (Exception e) {
			logger.error("导入数据接口出错！", e);
		}
    	return null;
    }
    
    @ApiOperation(value = "根据ID查询单个站点信息")
    @RequestMapping(value = "{id}", method = { RequestMethod.GET })
    @ApiImplicitParam(paramType = "path", name = "id", value = "站点ID", dataType = "Long", required = true)
    public ResultModel getBranchById(@PathVariable Long id) {
        ResultModel model = new ResultModel();
        try {
            TBranch data = branchService.getBranchById(id);
            model.setData(new JSONObject().fluentPut("result", data));
        }catch (Exception e){
        	model.setSub_code(ResultModel.SUB_CODE_SYSTEM_ERROR);
        	model.setSub_msg(e.getMessage());
            logger.error("根据ID查询站点信息出错！id：" + id, e);
        }
        return model;
    }

    @ApiOperation(value = "新增站点信息")
    @RequestMapping(value = "/add", method = { RequestMethod.POST })
    public ResultModel addBranch(TBranch tBranch) {
        ResultModel model = new ResultModel();
        try {
			if(StringUtils.isBlank(tBranch.getBranchName())){
				throw new BusinessException("站点名称不能为空，添加失败");
			}
			if(StringUtils.isBlank(tBranch.getBranchCode())){
				throw new BusinessException("站点编码不能为空，添加失败");
			}
			if(tBranch.getBranchFromType() ==null){
				throw new BusinessException("站点所属类型不能为空，添加失败");
			}
			//校验站点名称唯一信息
        	List<TBranch> listByName = branchService.getByNameOrId(null,tBranch.getBranchName().trim());
        	if(listByName.size() >0){
        		return new ResultModel(0, 1, new JSONObject().fluentPut("sub_msg" , "站点名称已存在，添加失败！"));
        	}
        	//校验站点编码唯一信息
        	List<TBranch> listByCode = branchService.getByCodeOrId(null,tBranch.getBranchCode().trim());
        	if(listByCode.size() >0){
        		return new ResultModel(0, 1, new JSONObject().fluentPut("sub_msg" , "站点编码已存在，添加失败！"));
        	}
        	StringBuffer sb = new StringBuffer();
        	String carType = tBranch.getUnavailableCarType();
        	if(StringUtils.isNotBlank(carType)){
        		String[] strs = carType.split(",");
        		for (int i = 0; i < strs.length; i++) {
        			String data = strs[i].trim();
					if(StringUtils.isNotBlank(strs[i])){
						sb.append(data).append(",");
					}
					if(i==strs.length-1){
						sb.deleteCharAt(sb.length()-1);
					}
				}
        		tBranch.setUnavailableCarType(sb.toString());
        	}
            int result = branchService.insertBranch(tBranch);
            if(result > 0){
            	model.setData(new JSONObject().fluentPut("result" , "添加成功"));
	        }else{
	        	model.setSub_code(1);
	        	model.setData(new JSONObject().fluentPut("sub_msg" , "添加失败"));
	        }
        } catch(BusinessException e){
        	model.setSub_code(1);
       	 	model.setData(new JSONObject().fluentPut("sub_msg" , e.getMessage()));
        } catch (Exception e) {
        	model.setSub_code(1);
        	model.setSub_msg("添加异常");
            logger.error("新增站点时发生异常！", e);
        }
        return model;
    }

    @ApiOperation(value = "修改站点信息")
    @RequestMapping(value = "/update", method = { RequestMethod.POST })
    public ResultModel updateBranch(TBranch tBranch) {
		ResultModel model = new ResultModel();
		try {
			if(StringUtils.isBlank(tBranch.getId().toString())){
				throw new BusinessException("数据为空，修改失败");
			}
			if(StringUtils.isBlank(tBranch.getBranchName())){
				throw new BusinessException("站点名称不能为空，修改失败");
			}
			if(StringUtils.isBlank(tBranch.getBranchCode())){
				throw new BusinessException("站点编码不能为空，修改失败");
			}
			if(tBranch.getBranchFromType() ==null){
				throw new BusinessException("站点所属类型不能为空，修改失败");
			}
			//校验站点名称唯一信息
        	List<TBranch> listByName = branchService.getByNameOrId(tBranch.getId().toString(),tBranch.getBranchName().trim());
        	if(listByName.size() >0){
        		return new ResultModel(0, 1, new JSONObject().fluentPut("sub_msg" , "站点名称已存在，修改失败！"));
        	}
        	//校验站点编码唯一信息
        	List<TBranch> listByCode = branchService.getByCodeOrId(tBranch.getId().toString(),tBranch.getBranchCode().trim());
        	if(listByCode.size() >0){
        		return new ResultModel(0, 1, new JSONObject().fluentPut("sub_msg" , "站点编码已存在，修改失败！"));
        	}
        	StringBuffer sb = new StringBuffer();
        	String carType = tBranch.getUnavailableCarType();
        	if(StringUtils.isNotBlank(carType)){
        		String[] strs = carType.split(",");
        		for (int i = 0; i < strs.length; i++) {
        			String data = strs[i].trim();
					if(StringUtils.isNotBlank(strs[i])){
						sb.append(data).append(",");
					}
					if(i==strs.length-1){
						sb.deleteCharAt(sb.length()-1);
					}
				}
        		tBranch.setUnavailableCarType(sb.toString());
        	}
			int result = branchService.updateBranch(tBranch);
			if(result > 0){
            	model.setData(new JSONObject().fluentPut("result" , "修改成功"));
	        }else{
	        	model.setSub_code(1);
	        	model.setData(new JSONObject().fluentPut("sub_msg" , "修改失败"));
	        }
        }catch (Exception e){
        	model.setSub_code(1);
        	model.setData(new JSONObject().fluentPut("sub_msg" , "修改失败"));
        	logger.error("修改站点时发生异常！"+e);
        }
		return model;
    }

    @ApiOperation(value = "删除站点信息")
    @RequestMapping(value = "/delete/{id}", method = { RequestMethod.DELETE })
    @ApiImplicitParam(paramType = "path", name = "id", value = "站点信息ID", dataType = "Long", required = true)
    public ResultModel deleteBranchById(@PathVariable Long id) {
    	ResultModel model = new ResultModel();
        try {
        	int result = branchService.deleteBranchById(id);
            if(result > 0){
            	model.setData(new JSONObject().fluentPut("result" , "删除成功"));
	        }else{
	        	model.setSub_code(1);
	        	model.setData(new JSONObject().fluentPut("sub_msg" , "删除失败"));
	        }
		} catch (BusinessException e) {
			model.setSub_code(1);
			model.setData(new JSONObject().fluentPut("sub_msg", e.getMessage()));
		} catch (Exception e) {
			model.setSub_code(1);
			model.setData(new JSONObject().fluentPut("sub_msg" , "删除失败"));
			logger.error("删除站点信息发生异常！id="+id, e);
		}
		return model;
    }
    
	@ApiOperation(value = "批量删除接口")
	@RequestMapping(value = "/deleteAll/{ids}", method = { RequestMethod.DELETE })
	@ApiImplicitParam(paramType = "path", name = "ids", value = "拼接需要删除的数据id串如：1,2,3,4", dataType = "String", required = true)
	public ResultModel deleteAll(@PathVariable String ids) {
		ResultModel model = new ResultModel();
        try {
        	int result = branchService.deleteBranchsByIds(ids);
            if(result > 0){
            	model.setData(new JSONObject().fluentPut("result" , "删除成功"));
	        }else{
	        	model.setSub_code(1);
	        	model.setData(new JSONObject().fluentPut("sub_msg" , "删除失败"));
	        }
        }catch (BusinessException e){
            logger.info("任务确认信息失败：", e);
            model.setSub_code(1);
            model.setData(new JSONObject().fluentPut("sub_msg", e.getMessage()));
            model.setSub_msg(e.getMessage());
        }catch (Exception e){
        	model.setSub_code(ResultModel.SUB_CODE_SYSTEM_ERROR);
            model.setSub_msg(e.getMessage());
        	logger.error("批量删除接口出错！", e);
        }
		return model;
	}
	
	@ApiOperation(value = "通过站点名称查询站点信息,可用来站点名称的唯一性", notes = "添加不需要ID,修改校验必要ID,返回Sub_code=0为可用,1为已存在!")
	@ApiImplicitParams({
		@ApiImplicitParam(paramType = "query", name = "id", value = "增加不需要传值，修改的时候需要传id", dataType = "String"),
		@ApiImplicitParam(paramType = "query", name = "name", value = "需要校验的站点名称", dataType = "String")})
	@RequestMapping(value = { "/getByNameOrId" }, method = RequestMethod.POST)
	public ResultModel getByNameOrId(String id, String name){
		ResultModel model = new ResultModel();
		try {
			//校验站点名称唯一信息
        	List<TBranch> list = branchService.getByNameOrId(id,name.trim());
        	if(list.size() >0){
        		model.setData(new JSONObject().fluentPut("result", "已存在"));
        	}else{
				model.setData(new JSONObject().fluentPut("result", "可用"));
			}
		} catch (Exception e) {
			model.setSub_code(1);
			model.setData(new JSONObject().fluentPut("sub_msg", "查询失败"));
		}
		return model;
	}
	@ApiOperation(value = "通过站点编号查询对象站点信息,可用来站点编号的唯一性", notes = "添加不需要ID,修改校验必要ID,返回Sub_code=0为可用,1为已存在!")
	@ApiImplicitParams({
		@ApiImplicitParam(paramType = "query", name = "id", value = "增加不需要传值，修改的时候需要传id", dataType = "String"),
		@ApiImplicitParam(paramType = "query", name = "name", value = "需要校验的站点编号", dataType = "String")})
	@RequestMapping(value = { "/getByCodeOrId" }, method = RequestMethod.POST)
	public ResultModel getByIdAndCode(String id, String name){
		ResultModel model = new ResultModel();
		try {
			//校验站点编号唯一信息
        	List<TBranch> list = branchService.getByCodeOrId(id,name.trim());
        	if(list.size() >0){
        		model.setData(new JSONObject().fluentPut("result", "已存在"));
        	}else{
				model.setData(new JSONObject().fluentPut("result", "可用"));
			}
		} catch (Exception e) {
			model.setSub_code(1);
			model.setData(new JSONObject().fluentPut("sub_msg", "查询失败"));
		}
		return model;
	}
	
    @ApiOperation(value = "通过ID查询操作日记接口,需要传id")
    @RequestMapping(value = "/getLogDataById", method = { RequestMethod.POST })
    public ResultModel getLogDataById(LogGirdQuery queryParam) {
		ResultModel model = new ResultModel();
		try {
			queryParam.setTableName("T_BRANCH");
            List<TLog> list = commonService.getLogDataById(queryParam);
            model.setCode(0);
            model.setSub_code(0);
            model.setData(new JSONObject().fluentPut("result", list));
            model.setPage(queryParam);
        }catch (Exception e){
        	model.setSub_code(1);
			model.setData(new JSONObject().fluentPut("sub_msg", null));
            logger.error("通过ID查询操作日记接口异常！", e);
        }
        return model;
    }
}
